import { get, post } from './request';
import { useUserInfo } from '@/stores/userInfo';
import { showToast } from 'vant';
import { decodeData, encodeData } from '@/utils/encryption';
import constants from '@/common/constants';
// @ts-ignore
import MD5 from './MD5.js';

interface Props {
  method: 'get' | 'post';
  url: string;
  data: any;
  opt: any;
}
type Request = (props: Props) => Promise<any>;

const request: Request = async function (props) {
  const userInfo = useUserInfo();
  const reqFn = props.method === 'get' ? get : post;
  try {
    // 处理签名
    const timestamp = new Date().getTime();
    const signstring = constants.APPTOKEN + 'appid=' + constants.APPID + 'timestamp=' + timestamp + constants.APPTOKEN;
    const sign = encodeData(MD5.base64Md5(signstring));
    // 处理参数
    const datas = props?.data || {};
    if (import.meta.env.DEV) {
      console.log('请求参数：', datas);
    }
    const pjsonData = encodeData(JSON.stringify(datas));
    // 处理请求头
    const headers = {
      ...(props.opt?.headers || {}),
      sign,
      timestamp,
      appid: constants.APPID,
    };
    // 发起请求
    const res = await reqFn(props.url, pjsonData, {
      // baseURL: import.meta.env?.DEV ? '' : import.meta.env?.VITE_ADMIN_BASE_URL || '',
      api: '/api',
      ...props.opt,
      headers,
    });
    // 返回值处理
    let responseResult: any;
    if (typeof res.data === 'string') {
      // 返回值为加密数据
      responseResult = decodeData(res.data);
    } else {
      responseResult = res.data;
    }
    if (typeof responseResult == 'string') {
      responseResult = JSON.parse(responseResult);
    }
    if (import.meta.env.DEV) {
      console.log(`${res.config.url}解密之后：`, responseResult);
    }
    if (responseResult.status === 0) {
      return Promise.resolve(responseResult);
    } else {
      // 登录失效
      if (responseResult.status === -2) {
        userInfo.loginOut();
      }
      showToast({
        message: responseResult?.message || responseResult?.msg || '网络异常',
        duration: 3500,
      });
      return Promise.reject(res);
    }
  } catch (err: any) {
    showToast({
      message: err.response.data?.message || err.response.data?.reason || '网络异常',
      duration: 3500,
    });
    return Promise.reject(err);
  }
};
export default request;
